#include "stdafx.h"
#include "MyGLWidget.h"
#include "glm/glm.hpp"
#include "Utils/Camera.h"
#include "QtApp.h"
#include "Graphics/Renderer.h"

#ifndef GL_MULTISAMPLE
#define GL_MULTISAMPLE  0x809D
#endif

using namespace RayFrame;

MyGLWidget::MyGLWidget(QWidget *parent) :
QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{

}

MyGLWidget::~MyGLWidget()
{
  internalDestroy();
}

void MyGLWidget::initializeGL()
{
  internalCreate();
}

void MyGLWidget::paintGL()
{
  if(m_app)
    m_app->Tick();
}

void MyGLWidget::resizeGL(int width, int height)
{
  if(m_app->GetCamera())
    m_app->GetCamera()->SetViewportSize(glm::vec2(width, height));
}

MouseButton MyGLWidget::translateMouseBtn(QMouseEvent *event)
{
  MouseButton btn;
  switch(event->button())
  {
  case Qt::LeftButton:
    btn = MOUSE_LEFT;
    break;
  case Qt::RightButton:
    btn = MOUSE_RIGHT;
    break;
  case Qt::MiddleButton:
    btn = MOUSE_MIDDLE;
    break;
  default:
    btn = MOUSE_NONE;
    break;
  }
  return btn;
}

void MyGLWidget::mousePressEvent( QMouseEvent *event )
{
  MouseButton btn = translateMouseBtn(event);
  if(m_app)
    RayFrame::g_qtApp->OnMouseButton(event->x(), event->y(), btn, true);
}

void MyGLWidget::mouseReleaseEvent( QMouseEvent *event )
{
  MouseButton btn = translateMouseBtn(event);
  RayFrame::g_qtApp->OnMouseButton(event->x(), event->y(), btn, false);
}

void MyGLWidget::mouseMoveEvent( QMouseEvent *event )
{

  RayFrame::g_qtApp->OnMouseMove(event->x(), event->y(), event->x(), event->y());
}

void MyGLWidget::internalCreate()
{
  timer = new QTimer(this);
  connect( timer, SIGNAL(timeout()), this, SLOT(updateGL()) );
  timer->start(10);

  m_isOK = true;
}

void MyGLWidget::internalDestroy()
{
  timer->stop();

  m_isOK = false;
}
